<?php
/********************************************************************
 *	Author:
 *		Jestery Liu <jestery@gmail.com>
 *		http://www.pte.cn
 *
 *	File:			FilenameParser.class.php
 *	Create Date:	2006-07-31 21:00:04 CST
 *******************************************************************/

require_once(PTE::getCoreLibsPath().'StringHelper.class.php');

/**
* @name FilenameParser
* @author jestery <jestery@gmail.com>
* @copyright PTE.cn
* @since 2005/10/10 15:00
*/
class FilenameParser
{
	/**
	* @var $uri (/www/abc/foo.php)
	*/
	public $uri;
	
	/**
	* @var $dirname (/www/abc/)
	*/
	public $dirname;
	
	/**
	* @var $basename (foo.php)
	*/
	public $basename;
	
	/**
	* @var $filename (foo)
	*/
	public $filename;
	
	/**
	* @var $extension (.php)
	*/
	public $extension;
	
	/**
	* @param $uri, An URI which contains the filepath and filename. For example, /www/foo/bar.php
	*/
	public function __construct($uri = '')
	{
		if (!empty($uri))
		{
			$this->uri = $uri;
			$this->parse();
		}
	}

	/**
	* @param $uri An URI which contains the filepath and filename. For example, /www/foo/bar.php
	* @return a key-value array
	*/
	public function parse($uri = '')
	{
		if (!empty($uri))
		{
			return self::staticParse($uri);
		}
		else
		{
			$pathInfo = self::staticParse($this->uri);
			$this->dirname = $pathInfo['dirname'];
			$this->basename = $pathInfo['basename'];
			$this->filename = $pathInfo['filename'];
			$this->extension = $pathInfo['extension'];
			return $pathInfo;
		}
	}
	
	private static function staticParse($uri)
	{
		$pathInfo = pathinfo($uri);
		$pathInfo['dirname'] = $pathInfo['dirname'].DIRECTORY_SEPARATOR;
		if (!empty($pathInfo['extension'])) {
			$pathInfo['extension'] = '.'.$pathInfo['extension'];
		}
		if ( StringHelper::strEndsWith($pathInfo['basename'], '.tar.gz') ) $pathInfo['extension'] = '.tar.gz';
		if ( StringHelper::strEndsWith($pathInfo['basename'], '.tar.bz2') ) $pathInfo['extension'] = '.tar.bz2';
		if ( StringHelper::strEndsWith($pathInfo['basename'], '.tar.bz') ) $pathInfo['extension'] = '.tar.bz';
		if ( StringHelper::strEndsWith($pathInfo['basename'], '.tar.bzip') ) $pathInfo['extension'] = '.tar.bzip';
		$pathInfo['filename'] = str_replace($pathInfo['extension'], '', $pathInfo['basename']);
		return $pathInfo;
	}
}
/* vim: set ts=4 sw=4 ff=unix: */
